import { ScannerPortDocument } from '@/generated/graphql'
import { useLoading } from '@/plugins/loading'
import { urqlOptions } from '@/plugins/urql'
import { useDockerApiPath } from '@/stores/dockerApi'
import { useCourseSessionStore } from '@/stores/useCourseStore'
import { DLog } from '@/utils/log'
import { createClient } from '@urql/vue'
import { message } from 'ant-design-vue'
import { last } from 'lodash-es'
import { defineComponent, h, reactive, watchEffect } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import leftBar from './leftBar'

/**
 * 终端展示页面
 */

export default defineComponent({
  components: {
    leftBar
  },
  props: {
    connectInfo: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['hidenTerminal'],
  setup(props, { emit }) {
    const { t } = useI18n()
    const router = useRouter()

    // 连接代理前缀
    const data = reactive<{
      webUrl?: string //iframe连接地址
    }>({
      webUrl: undefined
    })

    const { destroy: destroyLoading, update: updateLoading } = useLoading({
      visible: true,
      content: t('client.checkService')
    })

    const courseHook = useCourseSessionStore()

    //检查连接是否能访问
    const client = createClient(urqlOptions)
    const dockerApi = useDockerApiPath()
    let times = 0

    const checkURL = async (url: string) => {
      try {
        if (dockerApi.isWindows) {
          const addr = dockerApi.ip.split('/')[2]
          const ip = addr.split(':')[1]
          await client.query(ScannerPortDocument, {
            data: {
              host: ip,
              port: 33000
            }
          })
        } else {
          await fetch(url)
        }

        data.webUrl = url
        destroyLoading()
      } catch (error) {
        if (times >= 5) {
          destroyLoading()
          router.go(0)
        } else {
          console.log('重试')
          times++
          setTimeout(() => {
            checkURL(url)
          }, 5000)
        }
      }
    }

    watchEffect(() => {
      if (props.connectInfo) {
        DLog.Info('传入的连接信息', props.connectInfo)
        const _connectInfo = props.connectInfo
        if (!_connectInfo.path || !_connectInfo.ip) {
          destroyLoading()
          message.error(t('client.container_error'), 2.5, () => {
            router.go(0)
          })
        } else {
          if (courseHook.type === 'PRIVATE') {
            // 本地连接环境
            let url = ''
            if (dockerApi.isWindows) {
              url = dockerApi.routerPath
            } else {
              const connectPath = props.connectInfo.ip //获取到连接的代理ip
              const lastConnectPathArray = connectPath.split('.')
              const lastConnectPath = lastConnectPathArray[lastConnectPathArray.length - 1] //获取容器IP最后一位

              const instancePath = dockerApi.ip //实例的IP
              const instanceIPArray = instancePath.split('.')
              const lastInstanceIP = last(instanceIPArray) //获取实例IP最后一位
              url = ['container', lastConnectPath, lastInstanceIP, props.connectInfo.port].join('-')
              url = `/${url}/`
            }
            checkURL(`${url}`)
          } else {
            //云上环境连接
            console.log(props.connectInfo)

            const url = `//${props.connectInfo.ip}:${props.connectInfo.port}?${props.connectInfo.path}`
            checkURL(`${url}`)
          }
        }
      }
    })

    return () => (
      <div class="w-full h-full" style="cursor:none">
        {h(leftBar, {
          onHostSwitch: () => {
            emit('hidenTerminal', false)
          }
        })}
        <div class="flex items-center justify-center w-full h-full bg-white">
          <div class="w-full h-full">
            {data.webUrl && <iframe src={data.webUrl} class="w-full h-full" allow="clipboard-read; clipboard-write" />}
          </div>
        </div>
      </div>
    )
  }
})
